#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <string.h>

typedef struct Result
{
    char *msg;
    int len;
} Result;

void *red_thread (void *argv)
{
    char code = *((char *)argv);
    printf("红玫瑰线程开始执行，code=%c \n", code);

    while (1)
    {
        char input[10];
        // 读取用户输入
        fgets(input, 10, stdin);
        if (input[0] == code)
        {
            Result *result = malloc(sizeof(Result));
            char *msg = "红玫瑰线程离开";
            result->msg = msg;
            result->len = strlen(msg);
            printf("红玫瑰离开了 \n");
            // 结束返回result
            pthread_exit(result);
        }
        else
        {
            printf("红玫瑰线程线程还在等你：%s", input);
        }
    }
    
}



void *white_thread (void *argv)
{
    char code = *((char *)argv);
    printf("白玫瑰线程开始执行，code=%c \n", code);

    while (1)
    {
        char input[10];
        // 读取用户输入
        fgets(input, 10, stdin);
        if (input[0] == code)
        {
            Result *result = malloc(sizeof(Result));
            char *msg = "白玫瑰线程离开";
            result->msg = msg;
            result->len = strlen(msg);
            printf("白玫瑰离开了 \n");
            // 结束返回result
            return result;
        }
        else
        {
            printf("白玫瑰线程线程还在等你：%s", input);
        }
    }
}

int main(int argc, char const *argv[])
{
    
    pthread_t red_t;
    pthread_t white_t;

    char red_code = 'r';
    char white_code = 'w';

    Result *red_result;
    Result *white_result;

    pthread_create(&red_t, NULL, red_thread, &red_code);
    pthread_create(&white_t, NULL, white_thread, &white_code);


    pthread_join(red_t, (void **)&red_result);
    pthread_join(white_t, (void **)&white_result);

    printf("main线程得到了红玫瑰线程返回的结果：%s 长度：%d\n", red_result->msg, red_result->len);
    printf("main线程得到了白玫瑰线程返回的结果：%s 长度：%d\n", white_result->msg, white_result->len);

    // 释放内存
    free(red_result);
    free(white_result);

    return 0;
}
